package com.mlz.mlzmall.ui.activity.act.personal.myActivityPack;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.GoogDetailsActivity;
import com.mlz.mlzmall.ui.activity.act.main.MainActivity;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.GetMyPromotionResponse;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.MyActionBean;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.MyActivityRequestUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.MyCenterUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.MyShareBean;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.LoginActivity;
import com.mlz.mlzmall.ui.dialog.SharePopupWindow;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.Constans;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.CacheUtils;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.ui.utils.util.SharedUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.Tencent;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description 分享活动
 * Created by 安帅 on 2016/5/27 21:32.
 * PackageName com.mlz.mlzmall.ui.activity.act.personal.myActivityPack.
 * ProjectName mlzmall_android.
 */
public class ShareActivity extends VolleyBaseActivity implements IWeiboHandler.Response {
    private static final String TGA = "ShareActivity";
    int promotionId;
    int state;
    String shareId ;
    public List<GetMyPromotionResponse.DataBean.ListBean> pomitionlists;//我的活动列表
    private MyShareBean.DataBean sharePromotionDto;
    private List<MyShareBean.DataBean.ProgressBean> sharelist;
    MyActionBean myActionBean;//抽奖活动
    private int shareType;

    BaseUiListener baseUiListener;
    private Tencent mTencent;
    private IWeiboShareAPI mWeiboShareAPI;
    private IWXAPI wxApi;
    String sharemsg;
    private boolean isHaveImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share_actictiy);
        mTencent = Tencent.createInstance(Constans.QQAPP_ID, this.getApplicationContext());
        wxApi = WXAPIFactory.createWXAPI(this, Constans.APP_ID, false);
        wxApi.registerApp(Constans.APP_ID);

        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(ShareActivity.this, Constans.APP_KEY);
        mWeiboShareAPI.registerApp();
        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }
        //判断是否安装微博客户端
        if(!isInstall())
        {
            MyCenterUtils.ToastText("请安装客户端");
        }
        initData();
        assignViews();
        setViewContent();
        setViewClickListener();
    }

    private TopTitleView shareTopTitle;
    private WebView wvShareOutLogin;
    private ScrollView rlUnjoin;
    private RelativeLayout rlActivityShare;
    private ImageView ivSharePicture;
    private TextView tvNewsProduct;
    private TextView tvNewsExplain;
    private TextView tvTime;
    private TextView tvTimeFirst;
    private TextView tvTimeMiddle;
    private TextView tvTimeLast;
    private TextView tvShareShap;
    private TextView tvProgress;
    private TextView tvPie;
    private TextView tvRequireShareTimes;
    private RelativeLayout piTu;
    private ImageView ivRed;
    private ImageView ivBlueOver;
    private ImageView ivGray;
    private TextView tvFinish;
    private Button btnFinish;
    private ImageView btnFinishOver;
    private ImageView btnUnfinish;
    private TextView tvStatus;
    private ListView lvShare;
    private LinearLayout progressBarLl;
    private ProgressBar progressBar;
    private RelativeLayout rlBottom;
    private Button btnGetNow;
    private Button btnShareFriend;
    private Button btnShareOver;
    private LinearLayout llLoginNoShare;
    private LinearLayout btnNoLoginShare;
    private Button btnGoLogin;
    private Button btnGoBuy;

    private void assignViews() {
        shareTopTitle = (TopTitleView) findViewById(R.id.share_top_title);
        wvShareOutLogin = (WebView) findViewById(R.id.wv_share_out_login);
        rlUnjoin = (ScrollView) findViewById(R.id.rl_unjoin);
        rlActivityShare = (RelativeLayout) findViewById(R.id.rl_activity_share);
        ivSharePicture = (ImageView) findViewById(R.id.iv_share_picture);
        tvNewsProduct = (TextView) findViewById(R.id.tv_news_product);
        tvNewsExplain = (TextView) findViewById(R.id.tv_news_explain);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvTimeFirst = (TextView) findViewById(R.id.tv_time_first);
        tvTimeMiddle = (TextView) findViewById(R.id.tv_time_middle);
        tvTimeLast = (TextView) findViewById(R.id.tv_time_last);
        tvShareShap = (TextView) findViewById(R.id.tv_share_shap);
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        tvPie = (TextView) findViewById(R.id.tv_pie);
        tvRequireShareTimes = (TextView) findViewById(R.id.tv_requireShareTimes);
        piTu = (RelativeLayout) findViewById(R.id.pi_tu);
        ivRed = (ImageView) findViewById(R.id.iv_red);
        ivBlueOver = (ImageView) findViewById(R.id.iv_blue_over);
        ivGray = (ImageView) findViewById(R.id.iv_gray);
        tvFinish = (TextView) findViewById(R.id.tv_finish);
        btnFinish = (Button) findViewById(R.id.btn_finish);
        btnFinishOver = (ImageView) findViewById(R.id.btn_finish_over);
        btnUnfinish = (ImageView) findViewById(R.id.btn_unfinish);
        tvStatus = (TextView) findViewById(R.id.tv_status);
        lvShare = (ListView) findViewById(R.id.lv_share);
        progressBarLl = (LinearLayout) findViewById(R.id.progressBar_ll);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        rlBottom = (RelativeLayout) findViewById(R.id.rl_bottom);
        btnGetNow = (Button) findViewById(R.id.btn_get_now);
        btnShareFriend = (Button) findViewById(R.id.btn_share_friend);
        btnShareOver = (Button) findViewById(R.id.btn_share_over);
        llLoginNoShare = (LinearLayout) findViewById(R.id.ll_login_no_share);
        btnNoLoginShare = (LinearLayout) findViewById(R.id.btn_no_login_share);
        btnGoLogin = (Button) findViewById(R.id.btn_go_login);
        btnGoBuy = (Button) findViewById(R.id.btn_go_buy);


        setViewRequestContent();
    }

    private void setViewContent() {
        shareTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
    //    Toast.makeText(ShareActivity.this,"活动进度1setViewContent",Toast.LENGTH_SHORT).show();
        shareTopTitle.setTitleButtonContent("活动进度", null, null);
    }

    private void setViewClickListener() {
        shareTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                if (StringTools.shareid == 6) {
                    Intent intent0 = new Intent(ShareActivity.this, MainActivity.class);
                    startActivity(intent0);
                }
                finish();
           //     overridePendingTransition(R.anim.right_in, R.anim.left_out);
            }
        });
    }

    private void initData() {
        promotionId = Integer.parseInt(getIntent().getStringExtra("promotionId"));
        state = getIntent().getIntExtra("State", 100);
    }

    private void setListViewHeightBasedOnChildren(ListView lv_share) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = lv_share.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, lv_share);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            if (i == listAdapter.getCount() - 1 && isHaveImage) {
                totalHeight += listItem.getMeasuredHeight() + 55;
                break;
            }
            // 统计所有子项的总高度
            totalHeight += (listItem.getMeasuredHeight() + lv_share.getDividerHeight()) + 5;
        }

        ViewGroup.LayoutParams params = lv_share.getLayoutParams();
        params.height = totalHeight + (lv_share.getDividerHeight() * listAdapter.getCount());
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        lv_share.setLayoutParams(params);

    }

    @Override
    protected void onResume() {
        if (shareType == 1 && StringTools.shareback == 101) {
            shareSuccese(new MyHandler(), mContext);
            shareType = 10;
            StringTools.shareback = 100;
        } else if (shareType == 3 && StringTools.shareback == 103) {
            shareSuccese(new MyHandler(), mContext);
            shareType = 10;
            StringTools.shareback = 100;
        } else if (shareType == 2 && StringTools.shareback == 101) {
            shareSuccese(new MyHandler(), mContext);
            shareType = 10;
            StringTools.shareback = 100;
        }
        super.onResume();
    }

    /**
     * 微信分享 （这里仅提供一个分享网页的示例，其它请参看官网示例代码）
     *
     * @param flag(0:分享到微信好友，1：分享到微信朋友圈)
     */
    private void wechatShare(final int flag) {

        //这里替换一张自己工程里的图片资源
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    WXWebpageObject webpage = new WXWebpageObject();
                    webpage.webpageUrl = shareurl;

                    WXMediaMessage msg = new WXMediaMessage(webpage);
                    msg.title = sharetitle;
                    msg.description = sharecontent;
                    Bitmap thumb = imageLoader.loadImageSync(shareimage);
                    msg.setThumbImage(thumb);
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = String.valueOf(System.currentTimeMillis());
                    req.message = msg;
                    req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
                    wxApi.sendReq(req);
                    System.out.println("@@@@@==!!" + req.toString());
                } catch (Exception e) {
                    System.out.println("@@@@@==" + e.toString());
                    e.printStackTrace();
                }
            }
        }).start();
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String data = (String) msg.obj;
            shareover(data);
        }
    }

    public void shareSuccese(final Handler handler, final Context context) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                executeRequest(MyActivityRequestUtils.getMLZShareReturnRequset(context, promotionId, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Gson gson = new Gson();
                        MyShareBean myShareBean = gson.fromJson(s, MyShareBean.class);
                        sharemsg = myShareBean.getMsg();
                        Message message = handler.obtainMessage();
                        message.obj = sharemsg;
                        handler.sendMessage(message);
                    }
                }));

            }
        }).start();

    }

    String status2;
    String ifjoin;
    boolean finish;
    //返回的数据判断是否完成

    boolean finishtwo;
    String shareurl;
    String shareimage;
    String sharetitle;
    String sharecontent;

    //请求分享活动数据
    private void setViewRequestContent() {
        /**
         * 我的活动列表
         */
        executeRequest(MyActivityRequestUtils.getMLZActivityList(mContext, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i(TGA, "返回数据列表：" + s);
                Gson gson = new Gson();
                GetMyPromotionResponse pr = gson.fromJson(s, GetMyPromotionResponse.class);
                pomitionlists = pr.getData().getList();


            }
        }));
        /**
         * 我的抽奖活动
         */
        executeRequest(MyActivityRequestUtils.getMLZSweepStakes(mContext, promotionId, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i(TGA, "我的抽奖活动的数据：" + jsonObject.toString());
                Gson gosn = new Gson();
                MyActionBean myActionBean = gosn.fromJson(jsonObject.toString(), MyActionBean.class);
                if (myActionBean.getData() != null) {
                    status2 = myActionBean.getData().getStatus2();
                }

            }
        }));
        /**
         * 我的分享活动
         */
        executeRequest(MyActivityRequestUtils.getMLZShareRequset(mContext, promotionId, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i(TGA, "返回的分享活动的数据：" + s);

                Gson gson = new Gson();
                MyShareBean myShareBean = gson.fromJson(s, MyShareBean.class);

//                if (myShareBean.getStatus()==1003){
//                   return;
//                }
//                sharePromotionDto = myShareBean.getData();
//                sharelist = myShareBean.getData().getProgressDetails();
                if (myShareBean.getStatus()!=1003) {
                    sharePromotionDto = myShareBean.getData();
                    sharelist = myShareBean.getData().getProgressDetails();
                    final int type = sharePromotionDto.getType();
                    final String url = sharePromotionDto.getShareDescriptionUrl();
                    if (sharePromotionDto.getProductIds() != null) {
                        int nums = sharePromotionDto.getProductIds().size();
                        shareId = String.valueOf(sharePromotionDto.getProductIds().get(nums - 1));//获取数组最后一个索引的数字
                        Log.i(TGA, "shareId:" + shareId);
                    }


                    ifjoin = sharePromotionDto.getStatus();//分享状态
                    finish = sharePromotionDto.isGiftReceive();
                    //返回的数据判断是否完成

//                    finishtwo = myActionBean.getData().isGiftReceive();
                    shareurl = sharePromotionDto.getShare().getUrl();//分享的url
                    Log.i(TGA, "分享的url" + shareurl);


                    shareimage = sharePromotionDto.getShare().getImage();//分享的图片
                    Log.i(TGA, "分享的图片" + shareimage);
                    sharetitle = sharePromotionDto.getShare().getTitle();//分享的标题
                    Log.i(TGA, "分享的标题" + sharetitle);
                    sharecontent = sharePromotionDto.getShare().getContent();//分享的产品详情
                    final String shareproduct = sharePromotionDto.getImage();//分享出去的图片
                    final String productmessage = sharePromotionDto.getMessage();//分享产品的介绍
                    final String puroductdescribe = sharePromotionDto.getDescribe();//分享产品的介绍

                    final int progress = sharePromotionDto.getProgress();
                    final int requireShareTimes = sharePromotionDto.getRequireShareTimes();

                    //将后台的long型开始时间转换为正常日期并显示
                    Date dat_start = new Date(myShareBean.getData().getDateStart());
                    java.util.GregorianCalendar gc = new java.util.GregorianCalendar();
                    gc.setTime(dat_start);
                    SimpleDateFormat formatstart = new SimpleDateFormat("yyyy.MM.dd");
                   final String datastart = formatstart.format(gc.getTime());

                    //将后台的long型结束时间转换为正常日期并显示
                    Date dat_end = new Date(myShareBean.getData().getDateEnd());
                    java.util.GregorianCalendar ge = new java.util.GregorianCalendar();
                    ge.setTime(dat_end);
                    SimpleDateFormat formatend = new SimpleDateFormat("yyyy.MM.dd");
                    final String datasend = formatend.format(ge.getTime());

                    final String title = sharePromotionDto.getTitle();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //更新UI
                                    updateCustomInfoLayout(url, shareproduct, productmessage, puroductdescribe,
                                            datastart, datasend, progress, requireShareTimes, type, title, sharemsg, sharelist, pomitionlists);
                                    progressBarLl.setVisibility(View.GONE);
                                }
                            });
                        }
                    }).start();

                }else
                {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //更新UI
                                    updateCustomInfoLayout(null, null, null, null,
                                            null, null, 0, 0, 0, null, null, null, pomitionlists);
                                    progressBarLl.setVisibility(View.GONE);
                                }
                            });
                        }
                    }).start();

                }
            }
        }));


    }

    private void updateCustomInfoLayout(final String url, final String shareproduct, String productmessage, String puroductdescribe, String datastart, String datasend, int progress, int requireShareTimes, final int type, final String title, final String sharemsg, final List sharelist, final List pomitionlists) {
        //判断是否登陆

        final boolean islogin = CacheUtils.getBoolean(ShareActivity.this, "Logined", false);//判断是否登陆
//        Toast.makeText(ShareActivity.this, "islogin=" + islogin, Toast.LENGTH_SHORT).show();
//        String islogin = ACache.get(mContext).getAsString("islogin");
        if (islogin) {//如果登录的话
            //从主界面跳转过来
     //       Toast.makeText(ShareActivity.this, "StringTools.shareid=" + StringTools.shareid + MyApplication.getInstance().isLogin(), Toast.LENGTH_SHORT).show();
            if (StringTools.shareid == 6) {

                if (status2.equals("JOINED")) {
                    rlActivityShare.setVisibility(View.VISIBLE);
                    rlUnjoin.setVisibility(View.VISIBLE);
                    btnShareFriend.setVisibility(View.VISIBLE);//分享好友的按钮
      //              Toast.makeText(ShareActivity.this,"活动进度2从主界面跳转过来",Toast.LENGTH_SHORT).show();
                    shareTopTitle.setTitleButtonContent("活动进度", null, null);//显示标题
                    imageLoader.displayImage(shareproduct, ivSharePicture, options);//分享商品的图片
                    tvNewsProduct.setText(productmessage);//分享产品的介绍
                    tvNewsExplain.setText(puroductdescribe);//分享产品的介绍
                    tvTimeFirst.setText(datastart);
                    tvTimeLast.setText(datasend);
                    tvProgress.setText(String.valueOf(progress));
                    tvRequireShareTimes.setText(String.valueOf(requireShareTimes));

                    if (sharelist != null) {
                        lvShare = (ListView) findViewById(R.id.lv_share);
                        lvShare.setAdapter(new MyAdapter());
                        setListViewHeightBasedOnChildren(lvShare);
                    }

                    if (pomitionlists != null) {
                        System.out.println("******++++" + state);
                        if (state == 1) {
                            tvFinish.setText("0%");
                            tvFinish.setTextColor(Color.rgb(83, 203, 199));
                            btnUnfinish.setVisibility(View.VISIBLE);
                            tvStatus.setText("已过期");
                            ivGray.setVisibility(View.VISIBLE);

                        } else if (state == 2 || state == 3 || state == 4) {

                            tvFinish.setTextColor(Color.rgb(83, 203, 199));
                            tvFinish.setText("0%");
                            ivGray.setVisibility(View.VISIBLE);
                            btnUnfinish.setVisibility(View.VISIBLE);
                            tvStatus.setText("未完成");
                        } else if (state == 5) {
                            tvFinish.setText("100%");
                            ivRed.setVisibility(View.VISIBLE);
                            btnFinish.setVisibility(View.VISIBLE);

                        } else if (state == 6 || state == 7) {
                            tvFinish.setText("100%");
                            ivBlueOver.setVisibility(View.VISIBLE);
                            btnFinishOver.setVisibility(View.VISIBLE);
                            tvStatus.setText("已领取");
                        } else {

                            if (sharePromotionDto.isGiftReceive() == true) {
                                tvFinish.setText("100%");
                                btnFinishOver.setVisibility(View.VISIBLE);
                                ivBlueOver.setVisibility(View.VISIBLE);
                                tvStatus.setText("已领取");
                            } else {
                                tvFinish.setText("0%");
                              //  btnFinish.setVisibility(View.VISIBLE);
                              //  ivRed.setVisibility(View.VISIBLE);
                              // ivBlueOver.setVisibility(View.VISIBLE);
                                ivGray.setVisibility(View.VISIBLE);
                            }

                        }
                    }

                } else {
                    shareTopTitle.setTitleButtonContent("分享有礼", null, null);//显示标题
                    wvShareOutLogin.setVisibility(View.VISIBLE);
                    wvShareOutLogin.getSettings().setJavaScriptEnabled(true);//webview的适配
                    wvShareOutLogin.loadUrl(url);//登录状态

                    btnGetNow.setVisibility(View.VISIBLE);//登陆上后显示的按钮
                    btnGetNow.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setClass(ShareActivity.this, GoogDetailsActivity.class);
                            StringTools.shareId = Integer.valueOf(shareId);
                            StringTools.shareid = 1;
                            startActivity(intent);
                        }
                    });


                }

            } else if (StringTools.shareid == 4) {//从登录界面跳转过来
      //          Toast.makeText(ShareActivity.this, "从登录界面跳转过来", Toast.LENGTH_SHORT).show();
                shareTopTitle.setTitleButtonContent("分享有礼", null, null);//显示标题
                wvShareOutLogin.setVisibility(View.VISIBLE);

                wvShareOutLogin.getSettings().setJavaScriptEnabled(true);//webview的适配
                wvShareOutLogin.loadUrl(url);//登录状态

                btnGetNow.setVisibility(View.VISIBLE);//登陆上后显示的按钮

                btnGetNow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(ShareActivity.this, GoogDetailsActivity.class);
                        if(shareId!=null) {
                            StringTools.shareId = Integer.valueOf(shareId);
                        }else
                        {
                            StringTools.shareId = 0;
                        }
                        StringTools.shareid = 1;
                        startActivity(intent);
                    }
                });
                //从我的活动界面跳转过来
            } else if (StringTools.shareid == 5) {
                rlActivityShare.setVisibility(View.VISIBLE);
                if (ifjoin.equals("UNJOINED") || ifjoin.equals("JOINED")) {
                    rlUnjoin.setVisibility(View.VISIBLE);
                    btnShareFriend.setVisibility(View.VISIBLE);//分享好友的按钮
                    //显示标题
        //            Toast.makeText(ShareActivity.this,"活动进度3从我的活动界面跳转过来",Toast.LENGTH_SHORT).show();
                    shareTopTitle.setTitleButtonContent("活动进度", null, null);
                    imageLoader.displayImage(shareproduct, ivSharePicture, options);//分享商品的图片
                    tvNewsProduct.setText(productmessage);//分享产品的介绍
                    tvNewsExplain.setText(puroductdescribe);//分享产品的介绍
                    tvTimeFirst.setText(datastart);
                    tvTimeLast.setText(datasend);
                    tvProgress.setText(String.valueOf(progress));
                    tvRequireShareTimes.setText(String.valueOf(requireShareTimes));

                    if (sharelist != null) {
                        lvShare = (ListView) findViewById(R.id.lv_share);
                        lvShare.setAdapter(new MyAdapter());
                        setListViewHeightBasedOnChildren(lvShare);    //让Scollview 和listview同时滑动
                    }
                    if (pomitionlists != null) {
                        System.out.println("******@@@@@@" + state);
                        if (state == 1) {
                            tvFinish.setTextColor(Color.rgb(83, 203, 199));
                            tvFinish.setText("0%");
                            btnUnfinish.setVisibility(View.VISIBLE);
                            tvStatus.setText("已过期");
                            ivGray.setVisibility(View.VISIBLE);

                        } else if (state == 2 || state == 3 || state == 4) {
                            tvFinish.setTextColor(Color.rgb(83, 203, 199));
                            tvFinish.setText("0%");
                            btnUnfinish.setVisibility(View.VISIBLE);
                            tvStatus.setText("未完成");
                            ivGray.setVisibility(View.VISIBLE);
                        } else if (state == 5) {
                            if (sharePromotionDto.isGiftReceive() == true) {
                                tvFinish.setText("100%");
                                btnFinishOver.setVisibility(View.VISIBLE);
                                ivBlueOver.setVisibility(View.VISIBLE);
                                tvStatus.setText("已领取");
                            } else {
                                tvFinish.setText("100%");
                                btnFinish.setVisibility(View.VISIBLE);
                                ivRed.setVisibility(View.VISIBLE);
                            }
                        } else if (state == 6 || state == 7) {
                            tvFinish.setText("100%");
                            btnFinishOver.setVisibility(View.VISIBLE);
                            ivBlueOver.setVisibility(View.VISIBLE);
                            tvStatus.setText("已领取");
                        }
                    }
                } else if (ifjoin.equals("EXPIRED")) {
                    Button btn_share_over = (Button) findViewById(R.id.btn_share_over);
                    btn_share_over.setVisibility(View.VISIBLE);
         //         Toast.makeText(ShareActivity.this,"活动进度4EXPIRED",Toast.LENGTH_SHORT).show();
                    shareTopTitle.setTitleButtonContent("活动进度", null, null);//显示标题
                    imageLoader.displayImage(shareproduct, ivSharePicture, options);//分享商品的图片
                    tvNewsProduct.setText(productmessage);//分享产品的介绍
                    tvNewsExplain.setText(puroductdescribe);//分享产品的介绍
                    tvTimeFirst.setText(datastart);
                    tvTimeLast.setText(datasend);
                    tvProgress.setText(String.valueOf(progress));
                    tvRequireShareTimes.setText(String.valueOf(requireShareTimes));

                    if (pomitionlists != null) {
//                        pomitionlists.get(pomitionstate) == 5;
                        if (state == 4) {
                            tvFinish.setText("100%");
                            if (finish == true) {
                                btnFinishOver.setVisibility(View.VISIBLE);
                                ivBlueOver.setVisibility(View.VISIBLE);
                            } else if (finish == false) {
                                btnFinish.setVisibility(View.VISIBLE);
                                ivRed.setVisibility(View.VISIBLE);
                            }
                        } else if (state == 5) {
                            tvFinish.setText("100%");
                            tvFinish.setTextColor(Color.rgb(83, 203, 199));
                            btnUnfinish.setVisibility(View.VISIBLE);
                            ivGray.setVisibility(View.VISIBLE);
                        } else {
                            int number = progress / requireShareTimes;//显示百分号数
                            if (number == 0) {
                                tvFinish.setTextColor(Color.rgb(83, 203, 199));
                                tvFinish.setText("0%");
                                btnUnfinish.setVisibility(View.VISIBLE);
                                ivGray.setVisibility(View.VISIBLE);
                            } else {
                                tvFinish.setText("100%");
                                if (finish == true) {
                                    btnFinishOver.setVisibility(View.VISIBLE);
                                    ivBlueOver.setVisibility(View.VISIBLE);
                                } else if (finish == false) {
                                    btnFinish.setVisibility(View.VISIBLE);
                                    ivRed.setVisibility(View.VISIBLE);
                                }
                            }
                        }
                    }
                }
            }
            //如果没登陆的话
        } else {
            shareTopTitle.setTitleButtonContent("分享有礼", null, null);//显示标题
            wvShareOutLogin.setVisibility(View.VISIBLE);
            wvShareOutLogin.getSettings().setJavaScriptEnabled(true);//webview的适配
            wvShareOutLogin.loadUrl(url);//登录状态

            rlActivityShare.setVisibility(View.VISIBLE);
            llLoginNoShare.setVisibility(View.VISIBLE);//没登陆上显示的按钮
            btnGoLogin = (Button) findViewById(R.id.btn_go_login);//已购买请登录
            btnGoBuy = (Button) findViewById(R.id.btn_go_buy);//登录直接去购买
            btnGoLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(ShareActivity.this, LoginActivity.class);
                    StringTools.sharelogin = 1;
                    startActivity(intent);
                    finish();
                }
            });
            btnGoBuy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(ShareActivity.this, GoogDetailsActivity.class);
                    StringTools.shareId = Integer.valueOf(shareId);
                    StringTools.shareid = 1;
                    startActivity(intent);
                    finish();
                }
            });
        }
        btnFinish.setOnClickListener(new View.OnClickListener() {//点击兑换赠品传参数
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ShareActivity.this, ActionActivity.class);
                intent.putExtra("imageurl", shareproduct);
                intent.putExtra("type", type);
                intent.putExtra("promotionId", StringTools.m_nManufacturerId);
                intent.putExtra("state2", state);
                startActivity(intent);
                PopupMenu popupMenu = new PopupMenu(ShareActivity.this, btnFinish);
            }
        });
        //点击弹出分享界面
        btnShareFriend.setOnClickListener(new View.OnClickListener() {//分享点击
            @Override
            public void onClick(View v) {
                //判断是否登陆
                if (islogin) {
                    //进行分享的逻辑

                   SharePopupWindow.showSharePWindow(ShareActivity.this);
                   // rlShareDialog.setVisibility(View.VISIBLE);
                    SharePopupWindow.rl_weichat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            shareType = 1;
                            StringTools.TYPE = 100;
                            wechatShare(0);//分享到微信好友
                            SharePopupWindow.pWindow.dismiss();
                        }
                    });
                    SharePopupWindow.rl_wei_friend.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            shareType = 2;
                            StringTools.TYPE = 100;
                            wechatShare(1);//分享到微信朋友圈
                            SharePopupWindow.pWindow.dismiss();
                        }
                    });
                    SharePopupWindow.rl_qq_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            shareType = 3;
                            SharePopupWindow.pWindow.dismiss();
                            final Bundle params = new Bundle();
                            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                            params.putString(QQShare.SHARE_TO_QQ_TITLE, sharetitle);
                            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, sharecontent);
                            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareurl);
                            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, shareimage);
                            baseUiListener = new BaseUiListener();
                            mTencent.shareToQQ(ShareActivity.this, params, baseUiListener);
                        }
                    });
                    SharePopupWindow.rl_weibo_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!isInstall()) {
                                MyCenterUtils.ToastText("请安装客户端");
                            return;
                        }
                        shareType = 4;
                        mWeiboShareAPI.handleWeiboResponse(getIntent(), ShareActivity.this);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                                // 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
                                weiboMessage.mediaObject = getWebpageObj();
                                // 2. 初始化从第三方到微博的消息请求
                                SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
                                // 用transaction唯一标识一个请求
                                request.transaction = String.valueOf(System.currentTimeMillis());
                                request.multiMessage = weiboMessage;
                                // 3. 发送请求消息到微博，唤起微博分享界面
                                mWeiboShareAPI.sendRequest(request);
                            }
                        }).start();

                       SharePopupWindow.pWindow.dismiss();
                        }
                    });
                    SharePopupWindow.btn_cancal_share.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SharePopupWindow.pWindow.dismiss();
                        }
                    });
                } else {
                    //没登陆的话就到登陆界面
                    Intent intent = new Intent();
                    intent.setClass(ShareActivity.this, LoginActivity.class);
                    StringTools.sharelogin = 1;
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mTencent != null) {
            mTencent.onActivityResultData(requestCode, resultCode, data, baseUiListener);
        }
    }

    /**
     * 微博分享的内容
     *
     * @return
     */
    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.actionUrl = shareurl;
        mediaObject.identify = shareId;
        mediaObject.title = sharetitle;
        mediaObject.description = sharecontent;
        Bitmap bmp = imageLoader.loadImageSync(shareimage);
        mediaObject.setThumbImage(bmp);
        return mediaObject;
    }

    private Dialog mDialog;

    private void shareover(String sharemsg) {
        mDialog = new Dialog(mContext, R.style.pager_dialog);
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialogview_duihuan_address, null);
        mDialog.setContentView(view);
        TextView body = (TextView) view.findViewById(R.id.dialog_body);
        body.setText(sharemsg);
        view.findViewById(R.id.continue_shopping).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.show();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (shareType == 4)
            mWeiboShareAPI.handleWeiboResponse(intent, ShareActivity.this);

    }

    @Override
    public void onResponse(BaseResponse baseResponse) {

        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(ShareActivity.this, "分享返回", Toast.LENGTH_LONG)
                        .show();
                shareSuccese(new MyHandler(), mContext);
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(ShareActivity.this, "分享失败", Toast.LENGTH_LONG)
                        .show();
                break;
            default:
                break;
        }
    }

    boolean isInstall() {
        try {
            ShareActivity.this.getPackageManager().getPackageInfo("com.sina.weibo", 0);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return sharelist.size();
        }


        @Override
        public Object getItem(int position) {
            return sharelist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.share_list_name, null);
                vh = new ViewHolder();
                vh.tv_time_text = (TextView) convertView.findViewById(R.id.tv_time_text);
                vh.tv_time_over = (TextView) convertView.findViewById(R.id.tv_time_over);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            if (sharelist != null) {
                vh.tv_time_text.setText(sharelist.get(position).getMsg());


                //将后台的long型开始时间转换为正常日期并显示
                Date dat_start = new Date(sharelist.get(position).getDate());
                java.util.GregorianCalendar gc = new java.util.GregorianCalendar();
                gc.setTime(dat_start);
                SimpleDateFormat formatstart = new SimpleDateFormat("yyyy-MM-dd");
                String sb = formatstart.format(gc.getTime());
                vh.tv_time_over.setText(sb);
            }
            return convertView;
        }

        class ViewHolder {
            TextView tv_time_text;
            TextView tv_time_over;
        }
    }

}
